package com.gg.hj.controller;
import com.gg.common.pojo.SysUsers;
import com.gg.hj.search.SysRolesSearch;
import com.gg.hj.search.SysUsersSearch;
import com.gg.hj.service.SysUsersService;
import com.gg.hj.view.FileView;
import com.gg.hj.view.SysRolesView;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

@Controller
public class SysUsersController {
    @Resource
    private SysUsersService sysUsersService;
//    TODO 登入验证
    @RequestMapping("/login.action")
    public String login(String account, String password){
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(account,password);
            usernamePasswordToken.setRememberMe(true);
            subject.login(usernamePasswordToken);
            SysUsers sysUsers = this.sysUsersService.loginService(account);
            Session session = subject.getSession();
            session.setAttribute("user",sysUsers);
        }catch (Exception e){
            System.out.println("账号或密码错误！！！");
            return "redirect:/loginPage/login.html";
        }
        return  "redirect:/com/gg/index.html";
    }

//    TODO 登入显示用户信息
    @ResponseBody
    @RequestMapping("/userShow.action")
    public SysUsers userShow(){
        Session session = SecurityUtils.getSubject().getSession();
        return (SysUsers)session.getAttribute("user");
    }
    //TODO 退出登入
    @RequestMapping("/loginOut.action")
    public String loginOut(){
        Session session = SecurityUtils.getSubject().getSession();
        session.removeAttribute("user");
        return "redirect:/loginPage/login.html";
    }


    //TODO 用户信息维护
    @ResponseBody
    @RequestMapping("/queryUserAll.action")
    public SysUsersSearch<SysUsers> queryUserAll(@RequestBody SysUsersSearch<SysUsers> sysUsersSearch) throws Exception {
        return this.sysUsersService.queryUserAllService(sysUsersSearch);
    }

    //TODO 根据登入人主键查询具有的角色
    @ResponseBody
    @RequestMapping("/searchQueryByIdRole.action")
    public SysRolesSearch<SysRolesView> searchQueryByIdRole(@RequestBody SysRolesSearch<SysRolesView> sysRolesSearch) throws Exception {
        return this.sysUsersService.searchQueryByIdRoleService(sysRolesSearch);
    }

    //TODO 授权 或 回收 角色
    @ResponseBody
    @RequestMapping("/AuthorizeOrRecycleRoles.action")
    public int AuthorizeOrRecycleRoles(int id,int[] checks,int[] noChecks) throws Exception {
        return this.sysUsersService.AuthorizeOrRecycleRolesService(id,checks,noChecks);
    }

    //TODO 查询账号是否相同
    @ResponseBody
    @RequestMapping("/searchQueryUsersAccount.action")
    public SysUsers searchQueryUsersAccount(String account) throws Exception {
        return this.sysUsersService.searchQueryUsersAccountService(account);
    }

    //TODO 注册账号
    @ResponseBody
    @RequestMapping("/registerAccount.action")
    public int registerAccount(SysUsers sysUsers) throws Exception {
        SimpleHash passwordMD5 = new SimpleHash("MD5",sysUsers.getPassword(), ByteSource.Util.bytes(sysUsers.getLoginId()), 1024);
        sysUsers.setPassword(String.valueOf(passwordMD5));//设置密码加密MD5
        return this.sysUsersService.insertSelectiveService(sysUsers);
    }
    //TODO 添加用户
    @ResponseBody
    @RequestMapping("/hj/saveAccount.action")
    public int saveAccount(SysUsers sysUsers,MultipartFile img, HttpSession session) throws Exception {
        //文件目录
        String saveDictory = session.getServletContext().getRealPath("com/gg/hj/img");
        //实例File文件对象
        File imgFile = new File(saveDictory);
        //判断工程下是否有img文件夹
        if(!imgFile.exists()) {
            System.out	.println("创建文件");
            imgFile.mkdir();//创建文件夹
        }
        //旧文件名称
        String oldFileName = img.getOriginalFilename();
        //新文件名称
        String newFileName = UUID.randomUUID()+oldFileName.substring(oldFileName.lastIndexOf("."));
        //新文件保存路径
        String savaPath= saveDictory+"\\"+newFileName;
        //新图片文件
        File newfile = new File(savaPath);
        //把上传存在内存中的文件内容写入目标文件中
        img.transferTo(newfile);
        sysUsers.setPhotoPath("hj/img/"+newFileName);;

        SimpleHash passwordMD5 = new SimpleHash("MD5",sysUsers.getPassword(), ByteSource.Util.bytes(sysUsers.getLoginId()), 1024);
        sysUsers.setPassword(String.valueOf(passwordMD5));//设置密码加密MD5

        return this.sysUsersService.insertSelectiveService(sysUsers);
    }
    //TODO 保存上传文件图片
    @ResponseBody
    @RequestMapping("/hj/saveFileImg.action")
    public FileView saveFileImg(MultipartFile img,HttpSession session) throws Exception {
        //文件目录
        String saveDictory = session.getServletContext().getRealPath("com/gg/hj/img");
        //实例File文件对象
        File imgFile = new File(saveDictory);
        //判断工程下是否有img文件夹
        if(!imgFile.exists()) {
            System.out	.println("创建文件");
            imgFile.mkdir();//创建文件夹
        }
        //旧文件名称
        String oldFileName = img.getOriginalFilename();
        //新文件名称
        String newFileName = UUID.randomUUID()+oldFileName.substring(oldFileName.lastIndexOf("."));
        //新文件保存路径
        String savaPath= saveDictory+"\\"+newFileName;
        //新图片文件
        File newfile = new File(savaPath);
        //把上传存在内存中的文件内容写入目标文件中
        img.transferTo(newfile);
        FileView fileView = new FileView();
        fileView.setImg("hj/img/"+newFileName);
        return fileView;
    }
    //TODO 更新个人资料
    @ResponseBody
    @RequestMapping("/hj/updateAccount.action")
    public SysUsers updateAccount(@RequestBody SysUsers sysUsers) throws Exception {
        System.out.println("-------------"+sysUsers);

        Session s = SecurityUtils.getSubject().getSession();
        SysUsers user= (SysUsers)s.getAttribute("user");

        if(sysUsers.getPassword().equals(user.getPassword())){
            sysUsers.setPassword(null);
        }else{
            SimpleHash passwordMD5 = new SimpleHash("MD5",sysUsers.getPassword(), sysUsers.getLoginId(),1024);
            sysUsers.setPassword(String.valueOf(passwordMD5));//设置密码加密MD5
        }
        System.out.println("--------"+sysUsers.getPhotoPath()!="");
        if(sysUsers.getPhotoPath()!=""){
            user.setPhotoPath(sysUsers.getPhotoPath());
            s.setAttribute("user",user);
        }
        this.sysUsersService.updateAccountService(sysUsers);
        return user;
    }
}
